const http = require('http')
const fs = require('fs')

// const url = "http://www.51ape.com/jay/"
// const singerName = '周杰伦'
// 歌曲多的歌手
function getData(sourceUrl, singerName, singerId) {
    let url = "",
        path = '\\..\\Data\\singerMusicInfo\\' + singerId + '.json'
    for (let i = 1; i < 30; i++) {
        if (i === 1) {
            url = sourceUrl + 'index.html'
        } else {
            url = sourceUrl + 'index_' + i + '.html'
        }
        httpGet(url, singerName, singerId).then(v => {
            let res = []
            // console.log(v[0], v[1])
            for (let i = 0; i < v.length; i += 2) {
                let name = v[i + 1].match(/(?<=-\s).*(?=\.)/g)
                res.push({
                    musicUrl: v[i],
                    musicName: name[name.length - 1]
                })
            }
            console.log(res, res.length)

            fs.readFile(__dirname + path, (err, data) => {
                if (err) {
                    fs.writeFile(__dirname + path, JSON.stringify(res), err => {
                        if (err) {
                            console.error(singerId)
                        } else {
                            // console.log('歌手歌曲信息文件新建成功！')
                        }
                    })
                } else {
                    let sourceData = JSON.parse(data)
                    sourceData.push(...res)
                    fs.writeFile(__dirname + path, JSON.stringify(sourceData), err => {
                        if (err) {
                            console.error('歌手歌曲信息文件存储失败！')
                        } else {
                            console.log('歌手歌曲信息文件存储成功！')
                        }
                    })
                }
            })
            // console.log(res.length)
            // result.push(v)
            // console.log(result[0])
        })
    }
}

function httpGet(url, singerName, singerId) {
    return new Promise((resolve, reject) => {
        http.get(url, res => {
            if (res.statusCode !== 200) { // 判断页码
                // console.log(url.match(/(?<=\.com\/).+(?=\/)/g)[0] + '的歌曲链接结束');
                // console.log(singerName + '的歌曲链接结束')
                // console.log('无')
                console.log('404')
                return
            }
            var html = ''
            res.on('data', data => {
                html += data
                // console.log(html)
                if (html.indexOf('<!--left_1-->') !== -1) {
                    res.destroy()
                }
            })

            res.on('end', () => {
                let res;
                // console.log(html.length)
                // 第一次筛选，缩小范围
                res = html.match(/(?<=\<a\shref=").*(?="\sclass="wm210)|(?<=t20d\sml_1"\stitle=").*(?="\>)/g).map(v => {
                    return v.replace(/\<strong\>|\<\/strong\>/g, '')
                })
                // 第二次筛选，精确筛选，后面可能会有几个不相关的，剔除
                // 从后往前遍历，最后一个符合的，一定含有歌手名称
                let i = res.length - 1;
                while (res[i].indexOf(singerName) === -1) i--;
                res.splice(i + 1)
                resolve(res)
                // result.push(res)
                // console.log(res, res.length)
            })
        }).on('error', err => {
            console.log(singerId)
        })
    })
}

module.exports.getUrlAndNameMore = getData